package com.xuhai.movie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xuhai.movie.bean.Director;
import com.xuhai.movie.bean.Movie;
import com.xuhai.movie.mapper.DirectorMapper;
import com.xuhai.movie.mapper.MovieMapper;
import com.xuhai.movie.service.DirectorService;
import com.xuhai.movie.util.PageUtil;
import com.xuhai.movie.util.RTException;
import com.xuhai.movie.util.ResultJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author PangJunjie
 * @Date 2022/4/12/012
 */
@Service
@Transactional
public class DirectorServiceImpl implements DirectorService {

    @Autowired
    private DirectorMapper directorMapper;

    @Autowired
    private MovieMapper movieMapper;

    @Override
    public ResultJson getPage(int page, int limit, Director director) {
        PageHelper.startPage(page,limit);
        List<Director> directorList = directorMapper.getAll(director);
        PageInfo<Director> pageInfo= new PageInfo<>(directorList);
        return ResultJson.ok().data(new PageUtil(pageInfo));
    }

    @Override
    public ResultJson getById(Integer directorId) {
        return ResultJson.ok().data(directorMapper.selectByPrimaryKey(directorId));
    }

    @Override
    public ResultJson getSelect() {
        Director director = new Director();
        director.setStatus(1);
        return ResultJson.ok().data(directorMapper.getAll(director));
    }

    @Override
    public void saveOrUpdate(Director director) {
        if(director.getDirectorId()==null){
            directorMapper.insertSelective(director);
        }else{
            directorMapper.updateByPrimaryKeySelective(director);
        }
    }

    @Override
    public void deleteById(Integer directorId) {
        Movie movie = new Movie();
        movie.setDirectorId(directorId);
        List<Movie> movieList=movieMapper.getAll(movie);
        if(movieList.size()>0){
            throw new RTException("该导演已被使用，不得删除！");
        }
        directorMapper.deleteByPrimaryKey(directorId);
    }
}
